package algorithm.leetcode.I201to400;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class Q347 {

    public int[] topKFrequent(int[] nums, int k) {
        int[] result = new int[k];
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int num : nums) map.put(num, map.getOrDefault(num, 0)+1);

        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int num = entry.getKey(), count = entry.getValue();

            // 始终维护大小为K的最小堆,顶部元素要被替换
            if (pq.size() == k && pq.peek()[1] < count) {
                pq.poll();
                pq.offer(new int[]{num, count});
            }
            // 堆大小不超过K直接往里添加
            else pq.offer(new int[]{num, count});
        }
        for (int i = 0; i < k; i++) result[i] = pq.poll()[0];
        return result;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }

        System.out.println("====================");

        for (int i = 0; i < 10; ++i) {
            System.out.println(i);

        }
    }

}
